<template>
	<div class="admin-container">
		<!-- 搜索栏 -->
		<div class="search-bar">
			<el-row :gutter="20">
				<el-col :span="4">
					<el-input v-model="searchParams.username" placeholder="请输入用户名" clearable
						@keyup.enter.native="searchByUsername">
					</el-input>
				</el-col>
				<el-col :span="4">
					<el-input v-model="searchParams.email" placeholder="请输入邮箱" clearable
						@keyup.enter.native="searchByEmail">
					</el-input>
				</el-col>
				<el-col :span="16">
					<el-button type="primary" @click="searchByUsername">搜索用户名</el-button>
					<el-button type="primary" @click="searchByEmail">搜索邮箱</el-button>
					<el-button type="success" @click="showAddDialog">新增</el-button>
				</el-col>
			</el-row>
		</div>
		<div class="operation-bar">
			<el-button size="mini" @click="confirmAndDelete">批量删除</el-button>
		</div>
		<!-- 信息展示区 -->
		<div class="table-container">
			<el-table
			  :data="tableData"
			  style="width: 100%"
			  border
			  v-if="tableData.length > 0"
			  @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55"></el-table-column>
				<el-table-column prop="id" label="ID" width="180">
				</el-table-column>
				<el-table-column prop="username" label="用户名">
				</el-table-column>
				<el-table-column label="头像">
					<template slot-scope="scope">
						<img :src="scope.row.img" alt="User Avatar" class="avatar">
					</template>
				</el-table-column>
				<el-table-column prop="email" label="邮箱">
				</el-table-column>
				<el-table-column prop="phone" label="电话">
				</el-table-column>
				<el-table-column prop="integral" label="积分">
				</el-table-column>
				<el-table-column prop="name" label="VIP等级">
				</el-table-column>
				<el-table-column prop="create_time" label="创建时间">
					<template slot-scope="scope">
						{{ formatDate(scope.row.create_time) }}
					</template>
				</el-table-column>
				<el-table-column prop="update_time" label="更新时间">
					<template slot-scope="scope">
						{{ formatDate(scope.row.update_time) }}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="240">
					<template slot-scope="scope">
						<el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
						<el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div v-else class="no-data">
				<p>没有找到匹配的数据</p>
			</div>
		</div>
		<!-- 分页组件 -->
		<div class="pagination-container">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page.sync="currentPage" :page-size.sync="pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="allData.length">
			</el-pagination>
		</div>
		<!-- 编辑对话框 -->
		<el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="30%">
			<el-form :model="currentRow" :rules="editRules" ref="editForm">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="currentRow.username"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="currentRow.email"></el-input>
				</el-form-item>
				<el-form-item label="电话" prop="phone">
					<el-input v-model="currentRow.phone"></el-input>
				</el-form-item>
				<el-form-item label="积分" prop="integral">
					<el-input v-model="currentRow.integral"></el-input>
				</el-form-item>
				<el-form-item label="会员等级" prop="membership_id">
				  <el-select v-model="currentRow.membership_id" placeholder="请选择会员等级">
				    <el-option
				      v-for="level in membershipLevels"
				      :key="level.id"
				      :label="level.name"
				      :value="level.id">
				    </el-option>
				  </el-select>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleUpdate">更新</el-button>
			</span>
		</el-dialog>
		<!-- 新增对话框 -->
		<el-dialog title="新增用户" :visible.sync="addDialogVisible" width="30%">
			<el-form :model="addUser" :rules="addRules" ref="addForm">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="addUser.username"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="addUser.email"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input type="password" v-model="addUser.password"></el-input>
				</el-form-item>
				<el-form-item label="确定密码" prop="confirmPassword">
					<el-input type="password" v-model="addUser.confirmPassword"></el-input>
				</el-form-item>
				<el-form-item label="验证码" prop="code">
					<el-input v-model="addUser.code"></el-input>
					<el-button type="primary" @click="sendVerificationCode">获取验证码</el-button>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleAdd">确定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import axios from 'axios';
	import {
		Input,
		Row,
		Col,
		Button,
		Table,
		TableColumn,
		Dialog,
		Form,
		FormItem,
		Pagination,
		Message
	} from 'element-ui';

	export default {
		name: 'UserTable',
		components: {
			'el-input': Input,
			'el-row': Row,
			'el-col': Col,
			'el-button': Button,
			'el-table': Table,
			'el-table-column': TableColumn,
			'el-dialog': Dialog,
			'el-form': Form,
			'el-form-item': FormItem,
			'el-pagination': Pagination
		},
		data() {
			return {
				allData: [], // 存储所有数据
				tableData: [], // 存储当前页的数据
				searchParams: {
					username: '',
					email: ''
				},
				selectedRows: [],
				editDialogVisible: false,
				currentRow: {
					id: null,
					username: '',
					email: '',
					phone: '',
					integral: 0,
					name: ''
				},
				addDialogVisible: false,
				addUser: {
					username: '',
					email: '',
					password: '',
					confirmPassword: '',
					code: ''
				},
				editRules: {
					username: [{
							required: true,
							message: '请输入用户名',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 15,
							message: '用户名长度为3-15个字符',
							trigger: 'blur'
						}
					],
					email: [{
							required: true,
							message: '请输入邮箱地址',
							trigger: 'blur'
						},
						{
							type: 'email',
							message: '请输入正确的邮箱地址',
							trigger: 'blur,change'
						}
					]
				},
				addRules: {
					username: [{
							required: true,
							message: '请输入用户名',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 15,
							message: '用户名长度为3-15个字符',
							trigger: 'blur'
						}
					],
					email: [{
							required: true,
							message: '请输入邮箱地址',
							trigger: 'blur'
						},
						{
							type: 'email',
							message: '请输入正确的邮箱地址',
							trigger: 'blur,change'
						}
					],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: 'blur'
						},
						{
							min: 6,
							max: 20,
							message: '密码长度为6-20个字符',
							trigger: 'blur'
						}
					],
					confirmPassword: [{
							required: true,
							message: '请确认密码',
							trigger: 'blur'
						},
						{
							validator: (rule, value, callback) => {
								if (value !== this.addUser.password) {
									callback(new Error('两次密码输入不一致'));
								} else {
									callback();
								}
							},
							trigger: 'blur'
						}
					],
					code: [{
						required: true,
						message: '请输入验证码',
						trigger: 'blur'
					}]
				},
				currentPage: 1,
				pageSize: 10,
				membershipLevels: [] // 会员等级数据
			};
		},
		created() {
			this.fetchData();
			this.getMembershipLevels();
		},
		methods: {
			fetchData() {
				const token = localStorage.getItem('Authorization');
				if (!token) {
					this.$message.error('未授权访问');
					return;
				}
				const headers = {
					'Content-Type': 'application/json',
					'Authorization': token
				};
				axios.get('http://localhost:8887/user/UserfindAll', {
						headers
					})
					.then(response => {
						if (response.data.code === 200) {
							this.allData = response.data.data;
							this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this
								.currentPage * this.pageSize);
						} else {
							this.$message.error('获取数据失败: ' + response.data.message);
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						this.$message.error('请求失败，请检查网络或联系管理员');
					});
			},
			getMembershipLevels() {
				const token = localStorage.getItem('Authorization');
				if (!token) {
					this.$message.error('未授权访问');
					return;
				}
				const headers = {
					'Content-Type': 'application/json',
					'Authorization': token
				};
				axios.get('http://localhost:8887/Membershiptype/findAll', {
						headers
					})
					.then(response => {
						if (response.data.code === 200) {
							this.membershipLevels = response.data.data;
						} else {
							this.$message.error('获取会员等级数据失败');
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						this.$message.error('请求失败，请检查网络或联系管理员');
					});
			},
			formatDate(value) {
				const date = new Date(value);
				return new Intl.DateTimeFormat('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit',
					hour12: false
				}).format(date);
			},
			searchByUsername() {
				const token = localStorage.getItem('Authorization');
				const headers = {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Authorization': token,
				};
				axios.get('http://localhost:8887/user/selectName', {
						headers,
						params: {
							username: this.searchParams.username
						}
					})
					.then(response => {
						if (response.data.code === 200 && response.data.data.length > 0) {
							this.allData = response.data.data;
							this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this
								.currentPage * this.pageSize);
							this.currentPage = 1; // 重置当前页为 1
						} else {
							this.$message.error(response.data.message || '未找到匹配的用户');
							this.tableData = []; // 清空表格数据
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						this.$message.error('请求失败，请检查网络或联系管理员');
					});
			},
			 handleSelectionChange(val) {
			    this.selectedRows = val;
			  },
			confirmAndDelete() {
			    this.$confirm('确认执行此批量操作吗?', '提示', {
			      type: 'warning'
			    }).then(() => {
			      const ids = this.selectedRows.map(row => row.id);
			      if (ids.length === 0) {
			        this.$message.warning('请选择要操作的行');
			        return;
			      }
			      const payload = {
			        ids: ids,
			      };
			      const token = localStorage.getItem('Authorization');
			      const headers = {
			        'Content-Type': 'application/json',
			        'Authorization': token
			      };
			      axios.post('http://localhost:8887/user/admindelete', payload, {
			          headers
			        })
			        .then(response => {
			          if (response.data.code === 200) {
			            this.$message.success(response.data.message);
			            this.fetchData(); // 重新加载数据
			          } else {
			            this.$message.error(response.data.message);
			          }
			        })
			        .catch(error => {
			          console.error('请求失败:', error);
			          this.$message.error('请求失败，请检查网络或联系管理员');
			        });
			    }).catch(() => {
			      this.$message.info('已取消操作');
			    });
			  },
			searchByEmail() {
				const token = localStorage.getItem('Authorization');
				const headers = {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Authorization': token
				};
				axios.get('http://localhost:8887/user/selectemail', {
						headers,
						params: {
							email: this.searchParams.email
						}
					})
					.then(response => {
						if (response.data.code === 200 && response.data.data.length > 0) {
							this.allData = response.data.data;
							this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this
								.currentPage * this.pageSize);
							this.currentPage = 1; // 重置当前页为 1
						} else {
							this.$message.error(response.data.message || '未找到匹配的用户');
							this.tableData = []; // 清空表格数据
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						this.$message.error('请求失败，请检查网络或联系管理员');
					});
			},
			handleEdit(row) {
			  if (row) {
			    this.currentRow = {
			      ...row,
			      membership_id: row.membership_id
			    };
			    this.editDialogVisible = true;
			  } else {
			    console.error('Error: Row data is null');
			  }
			},
			handleDelete(id) {
				this.$confirm('确认删除这条记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					const token = localStorage.getItem('Authorization');
					const headers = {
						'Content-Type': 'application/x-www-form-urlencoded',
						'Authorization': token
					};
					axios.post('http://localhost:8887/user/deleteUserById', {
							id: id
						}, {
							headers
						})
						.then(response => {
							if (response.data.code === 200) {
								this.$message.success('删除成功');
								this.fetchData(); // 重新加载数据
							} else {
								this.$message.error('删除失败: ' + response.data.message);
							}
						})
						.catch(error => {
							console.error('请求失败:', error);
							this.$message.error('请求失败，请检查网络或联系管理员');
						});
				}).catch(() => {
					this.$message.info('已取消删除');
				});
			},
			handleAdd() {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						const token = localStorage.getItem('Authorization');
						const headers = {
							'Content-Type': 'application/json',
							'Authorization': token
						};
						axios.post('http://localhost:8887/user/register', this.addUser, {
								headers
							})
							.then(response => {
								if (response.data.code === 200) {
									this.$message.success('新增用户成功');
									this.addDialogVisible = false;
									this.fetchData();
								} else {
									this.$message.error('新增用户失败: ' + response.data.message);
								}
							})
							.catch(error => {
								console.error('请求失败:', error);
								this.$message.error('请求失败，请检查网络或联系管理员');
							});
					} else {
						this.$message.error('表单验证失败');
					}
				});
			},
			handleUpdate() {
			  this.$refs.editForm.validate((valid) => {
			    if (valid) {
			      const token = localStorage.getItem('Authorization');
			      const headers = {
			        'Content-Type': 'application/json',
			        'Authorization': token
			      };
			      axios.post('http://localhost:8887/user/updateUserById', this.currentRow, {
			        headers
			      })
			      .then(response => {
			        if (response.data.code === 200) {
			          this.$message.success('更新成功');
			          this.editDialogVisible = false;
			          this.fetchData(); // 重新加载数据
			        } else {
			          this.$message.error('更新失败: ' + response.data.message);
			        }
			      })
			      .catch(error => {
			        console.error('请求失败:', error);
			        this.$message.error('请求失败，请检查网络或联系管理员');
			      });
			    } else {
			      this.$message.error('表单验证失败');
			    }
			  });
			},
			showAddDialog() {
				this.addDialogVisible = true;
				this.addUser = {
					username: '',
					email: '',
					password: '',
					confirmPassword: '',
					code: ''
				};
			},
			sendVerificationCode() {
				const token = localStorage.getItem('Authorization');
				const headers = {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Authorization': token
				};
				axios.get('http://localhost:8887/user/sendCode', {
						headers,
						params: {
							email: this.addUser.email
						}
					})
					.then(response => {
						if (response.data.code === 200) {
							this.$message.success('验证码发送成功，请查收邮件');
						} else {
							this.$message.error('验证码发送失败: ' + response.data.message);
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						this.$message.error('请求失败，请检查网络或联系管理员');
					});
			},
			handleSizeChange(newSize) {
				this.pageSize = newSize;
				this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this
					.pageSize);
			},
			handleCurrentChange(newPage) {
				this.currentPage = newPage;
				this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this
					.pageSize);
			},
		}
	};
</script>

<style scoped>
	.admin-container {
		padding: 20px;
		max-width: 100%;
		overflow-x: auto;
	}

	.search-bar {
		margin-bottom: 20px;
	}

	.search-bar .el-row {
		display: flex;
		justify-content: space-between;
	}

	.search-bar .el-button {
		margin-left: 10px;
	}

	.table-container {
		margin-top: 20px;
		overflow-x: auto;
	}

	.no-data {
		text-align: center;
		padding: 20px;
	}

	.pagination-container {
		margin-top: 20px;
		text-align: left;
	}

	.dialog-footer {
		text-align: right;
	}

	.el-dialog__body {
		padding: 20px;
	}

	.el-form-item {
		margin-bottom: 20px;
	}

	.el-form-item__label {
		font-weight: bold;
	}

	.el-button--primary {
		background-color: #13ce66;
		border-color: #13ce66;
	}

	.el-button--primary:hover {
		background-color: #11b55e;
		border-color: #11b55e;
	}

	.avatar {
		width: 40px;
		/* 设置头像宽度 /
height: 40px; / 设置头像高度 /
border-radius: 50%; / 圆形头像 /
object-fit: cover; / 保证图片内容不失真 */
	}
</style>